package com.admin.system.service;

import com.admin.config.MinioConfig;
import com.admin.qujiang.mapper.YlDatakbWorkingPersonnelMapper;
import com.admin.qujiang.model.YlDatakbWorkingPersonnelModel;
import com.admin.system.mapper.IFileMapper;
import io.minio.PutObjectArgs;
import me.zhengjie.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MinioService {

    @Autowired
    private MinioConfig springConfig;
    @Autowired
    private IFileMapper fileMapper;

    @Value("${minio.url}")
    private String  URL;

    public String saveImg(MultipartFile file) throws Exception{
        String fileName = file.getOriginalFilename();
        //防止文件名称重复
        Random random = new Random();
        int rd = random.nextInt(100);
        fileName = System.currentTimeMillis() + rd + fileName;
        InputStream inputStream=file.getInputStream();
        //如果是图片文件就进行压缩
        if (ImageUtil.isImage(fileName)){
            inputStream=ImageUtil.getInputStream(
                    ImageUtil.setWatermark(
                            ImageUtil.compress(
                                    ImageIO.read(inputStream))),
                    ImageUtil.getFileExtention(fileName));
        }
        //存储桶名称
        String bucketName = "images";
        PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName)
                .stream(inputStream,inputStream.available(),-1).contentType(file.getContentType()).build();
        springConfig.minioClient().putObject(objectArgs);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,Object> data=new HashMap<>();
        data.put("url",URL+"/"+"images"+"/"+fileName);
        data.put("addTime",sdf.format(new Date()));
        //data.put("name",name);
        //data.put("type",type);
        //data.put("eventId",eventId);
        fileMapper.addFile(data);
        return URL+"/"+"images"+"/"+fileName;
    }
    public List<Map> getImagesList(String type,String name,String minId) throws Exception{
        return fileMapper.getImagesList(type,name,minId);
    }

}
